#include"Udpserver.hpp"
#include"memory"

#include<iostream>
#include<sys/io.h>
#include<sys/types.h>
#include<sys/socket.h>

int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        perror("缺少端口参数\n");
        exit(1);
    }
    std::string serverip=argv[1];
    uint16_t serveerport=std::stoi(argv[2]);

    int sockfd=::socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd<0)
    {
        std::cerr<<"socket creat is error"<<std::endl;
        exit(2);
    }
    std::cout<<"creat socket success"<<std::endl;

    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;
    server.sin_addr.s_addr=inet_addr(serverip.c_str());
    server.sin_port=htons(serveerport);

    while(true)
    {
        //发送数据
        std::string inbuffer;
        std::cout<<"请输入数据# ";
        std::getline(std::cin,inbuffer);
        ssize_t n=sendto(sockfd,inbuffer.c_str(),sizeof(inbuffer),0,SOC(&server),sizeof(server));

        //接收数据

        if(n>0)
        {
            char buffer[default_size];

            socklen_t len=sizeof(server);

            ssize_t m=recvfrom(sockfd,buffer,sizeof(buffer)-1,0,SOC(&server),&len);
            if(m>0)
            {
                buffer[m]=0;
                std::cout<<"客户端回显# "<<buffer<<std::endl;
            }
            else{
                break;
            }
        }
        else{
            break;
        }
    }

}